/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.framework.encryption;

import java.io.UnsupportedEncodingException;

/**
 * The Class ConversionUtil.
 *
 * @author Xi Wei
 */
public class ConversionUtil {

	/**
	 * Int to byte array.
	 *
	 * @param value the value
	 * @return the byte[]
	 */
	public static byte[] intToByteArray(int value) {
		return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
	}

	/**
	 * Byte array to int.
	 *
	 * @param b the b
	 * @return the int
	 */
	public static int byteArrayToInt(byte[] b) {
		return ((b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF));
	}

	/**
	 * Long to byte array.
	 *
	 * @param data the data
	 * @return the byte[]
	 */
	public static byte[] longToByteArray(long data) {
		return new byte[] { (byte) (int) (data >> 56 & 0xFF), (byte) (int) (data >> 48 & 0xFF),
				(byte) (int) (data >> 40 & 0xFF), (byte) (int) (data >> 32 & 0xFF), (byte) (int) (data >> 24 & 0xFF),
				(byte) (int) (data >> 16 & 0xFF), (byte) (int) (data >> 8 & 0xFF), (byte) (int) (data >> 0 & 0xFF) };
	}

	/**
	 * Byte array to long.
	 *
	 * @param data the data
	 * @return the long
	 */
	public static long byteArrayToLong(byte[] data) {
		if ((data == null) || (data.length != 8)) {
			return 0L;
		}

		return ((0xFF & data[0]) << 56 | (0xFF & data[1]) << 48 | (0xFF & data[2]) << 40 | (0xFF & data[3]) << 32
				| (0xFF & data[4]) << 24 | (0xFF & data[5]) << 16 | (0xFF & data[6]) << 8 | (0xFF & data[7]) << 0);
	}

	/**
	 * Byte 2 hex.
	 *
	 * @param bytes the bytes
	 * @return the string
	 */
	public static String byte2hex(byte[] bytes) {
		if (bytes == null) {
			return null;
		}

		String hs = "";
		String stmp = "";
		for (int n = 0; n < bytes.length; ++n) {
			stmp = Integer.toHexString(bytes[n] & 0xFF);
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}

	/**
	 * Hex 2 byte.
	 *
	 * @param hexString the hex string
	 * @return the byte[]
	 * @throws UnsupportedEncodingException the unsupported encoding exception
	 */
	public static byte[] hex2byte(String hexString) throws UnsupportedEncodingException {
		if (hexString == null) {
			return null;
		}

		byte[] b = hexString.getBytes("UTF-8");

		if (b.length % 2 != 0) {
			throw new IllegalArgumentException("Length is not odd!");
		}

		byte[] b2 = new byte[b.length / 2];

		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[(n / 2)] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}
}
